package com.yanglei.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JList;

import com.yanglei.util.CharacterUtil;
import com.yanglei.util.XMLUtil;

public class ServerMessageThread extends Thread {

	private Server server;

	private InputStream is;

	private OutputStream os;

	public ServerMessageThread(Server server, Socket socket) {
		try {
			this.server = server;

			this.is = socket.getInputStream();

			this.os = socket.getOutputStream();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 更新用户列表
	public void updateUserList() {
		// 获取用户名列表
		Set<String> users = this.server.getMap().keySet();

		Vector<String> vector = new Vector<String>();
		vector.addAll(users);

		// 将列表信息执空
		this.server.getDlm().clear();
		for (String s : vector)
			this.server.getDlm().addElement(s);

		String xml = XMLUtil.constructUserList(users);

		Collection<ServerMessageThread> cols = this.server.getMap().values();
		// 遍历每个线程 向每个用户发送在线用户列表
		for (ServerMessageThread smt : cols) {
			smt.sendMessage(xml);
		}
	}

	// 发送xml数据
	public void sendMessage(String message) {
		try {
			os.write(message.getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 踢出用户
	public void removeUser(String username, String type) {
		try {
			int t = Integer.parseInt(type);

			String xml = null;

			if (t == CharacterUtil.REMOVE_CLIENT) {

				xml = XMLUtil.construcRemoveClientXML();
				ServerMessageThread smt = this.server.getMap().get(username);
				smt.sendMessage(xml);
				this.server.getMap().remove(username);
				this.updateUserList();
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				byte[] buf = new byte[5000];
				int length = is.read(buf);

				// 客户端发来的消息
				String xml = new String(buf, 0, length);

				int type = Integer.parseInt(XMLUtil.extractType(xml));

				if (CharacterUtil.CLIENT_MESSAGE == type) {
					// who发来的消息
					String username = XMLUtil.extractUsername(xml);
					// 消息内容
					String content = XMLUtil.extracContent(xml);
					// 构造向所有客户端发送的消息
					String message = username + ": " + content;
					// 向所有客户端发送xml聊天数据
					String messageXML = XMLUtil
							.constructServerMessageXML(message);

					Map<String, ServerMessageThread> map = this.server.getMap();

					Collection<ServerMessageThread> cols = map.values();
					for (ServerMessageThread smt : cols) {
						smt.sendMessage(messageXML);
					}
				}
				// 关闭客户端窗口
				else if (CharacterUtil.CLOSE_CLIENT_WINDOW == type) {
					String username = XMLUtil.extractUsername(xml);

					// 向客户端发送一条确认信息
					ServerMessageThread smt = this.server.getMap()
							.get(username);
					// 构造客户端确认消息
					String confirmationXml = XMLUtil
							.constructCloseClientWindowConfirmationXML();

					smt.sendMessage(confirmationXml);

					// 从map中将该用户除去
					this.server.getMap().remove(username);
					// 更新在线用户列表
					this.updateUserList();

					this.is.close();

					this.os.close();

					break;// 结束该线程
				}

				// 私聊信息
				else if (CharacterUtil.SINGLE_CLIENT_SERVER == type) {
					// 从xml数据中解析出 私聊双方的名字 及聊天内容
					String username1 = XMLUtil.extractUsername(xml);//发送者
					String username2 = XMLUtil.extractUsername2(xml);//接收者
					String content = XMLUtil.extracContent(xml);

					// 构造要发出的消息
					String message = username1 + ":" + content;
					String messageXML1 = XMLUtil
							.constructSingleMessageXML(message,username1);
					String messageXML2=XMLUtil.constructSingleMessageXML(message, username2);

					// 遍历map找到对应的thread
					ServerMessageThread smt1 = this.server.getMap().get(
							username1);
					ServerMessageThread smt2 = this.server.getMap().get(
							username2);

					// 发送消息
					smt1.sendMessage(messageXML2);
					smt2.sendMessage(messageXML1);
				}
				// 私聊请求信息
				else if (CharacterUtil.SINGLE_REQUEST == type) {

					String username = XMLUtil.extractUsername(xml);// 接收请求者

					String username2 = XMLUtil.extractUsername2(xml);// 请求发起者

					String messageXML = null;
					if (!username2.equals(username)) {
						messageXML = XMLUtil.construcSingleRequestXML(username,
								username2);
					} else {
						messageXML = XMLUtil
								.constructSameNameSingleXML(username);
					}
					ServerMessageThread smt = this.server.getMap()
							.get(username);
					smt.sendMessage(messageXML);

				}
				// 返回请求信息
				else if (CharacterUtil.SINGLE_RESPONCE == type) {
					String username = XMLUtil.extractUsername(xml);// 接收请求者

					String username2 = XMLUtil.extractUsername2(xml);// 请求发起者

					// 得到返回的信息
					String message = XMLUtil.extracContent(xml);

					String messageXML = XMLUtil.construcSingleResponseXML(
							message, username, username2);

					ServerMessageThread smt = this.server.getMap()
							.get(username);

					smt.sendMessage(messageXML);
				}
				// 得到私聊窗口关闭的消息
				else if (CharacterUtil.SINGLE_CLIENT_CLOSE == type) {
					String username = XMLUtil.extractUsername(xml);
                    String username2=XMLUtil.extractUsername2(xml);//关闭窗口者
                    
					String messageXML = XMLUtil
							.constructCloseSingleClientWindowXML(username,username2);
					ServerMessageThread smt = this.server.getMap()
							.get(username);

					smt.sendMessage(messageXML);
				}
				// 请求文件传输
				else if (CharacterUtil.SEND_FILE_REQUEST == type) {
					String username = XMLUtil.extractUsername(xml);// 接收请求者

					String username2 = XMLUtil.extractUsername2(xml);// 请求发起者

					String message = XMLUtil.extracContent(xml);

					String messageXML = null;

					messageXML = XMLUtil.construcFileRequestXML(username,
							username2, message);

					ServerMessageThread smt = this.server.getMap()
							.get(username);
					smt.sendMessage(messageXML);
				}
				// 请求文件传输返回消息
				else if (CharacterUtil.SEND_FILE_RESPONSE == type) {
					// 请求发起者
					String sendName = XMLUtil.extractUsername(xml);

					// 接受请求者
					String recName = XMLUtil.extractUsername2(xml);

					String message = XMLUtil.extracContent(xml);

					String port = XMLUtil.extractPort(xml);

					String address = XMLUtil.extractAddress(xml);

					String messageXML = XMLUtil.construcSendFileResponseXML(
							message, sendName, recName, port, address);

					ServerMessageThread smt = this.server.getMap()
							.get(sendName);
					smt.sendMessage(messageXML);
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}
